﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using uTools;


public class Level9Memory : MonoBehaviour
{
    public List<TextButton> tbList = new List<TextButton>();
    public List<uTweenAlpha> imageTweenAlpha = new List<uTweenAlpha>();
    public List<uTweenAlpha> textTweenAlpah = new List<uTweenAlpha>();
    private List<string> strList = new List<string>();
    private List<int> activeTBIndexList = new List<int>();
    public GameLevelItem gameLevelItem;
    // Start is called before the first frame update
    void Start()
    {
        InitStrList();
        InitTextButton();

        Invoke("HideText", 2);

    }

    private void HideText()
    {
        int count = textTweenAlpah.Count;
        for(int i = 0;i <count;i++)
        {
            int tempIndex = i;
            textTweenAlpah[i].Play(PlayDirection.Forward);
            textTweenAlpah[tempIndex].onFinished.AddListener(() =>
            {
                textTweenAlpah[tempIndex].onFinished.RemoveAllListeners();
                tbList[tempIndex].button.enabled = true;
            });

            imageTweenAlpha[tempIndex].Play(PlayDirection.Forward);
        }
    }

    private void InitStrList()
    {
        strList.Add("q");
        strList.Add("t");
        strList.Add("z");
        strList.Add("g");
        strList.Add("i");
        strList.Add("h");
        strList.Add("w");
        strList.Add("l");
        strList.Add("k");

        int randomIndex = Random.Range(0, strList.Count);
        string tempStr = strList[randomIndex];
        strList.RemoveAt(randomIndex);
        strList.Add(tempStr);
    }

    void InitTextButton()
    {
        int count = tbList.Count;
        for (int i = 0; i < count; i++)
        {
            int tempIndex = i;
            tbList[i].Init(strList[tempIndex], () =>
            {
                if (GameCtrl.Instance.curGameState == GameState.Menu)
                    return;
                if (activeTBIndexList.Count > 5)
                    return;
                tbList[tempIndex].button.enabled = false;
                textTweenAlpah[tempIndex].Play(PlayDirection.Reverse);
                textTweenAlpah[tempIndex].onFinished.AddListener(() => { JudgeResult(); });
                activeTBIndexList.Add(tempIndex);
            });

            tbList[i].button.enabled = false;
        }
    }

    private void JudgeResult()
    {
        if (activeTBIndexList.Count >= 5)
        {
            bool result = true;
            int count = activeTBIndexList.Count;
            for(int i = 0;i < count;i++)
            {
                if (!UConst.Str_TargetLove.Contains(tbList[activeTBIndexList[i]].text.text))
                {
                    result = false;
                    break;
                }
            }
            gameLevelItem.TriggerResult(result);
        }
    }


}
